# -*- coding: utf-8 -*-
"""Misc utilities"""
from sqlobject import classregistry
from cherrypy import request
from turbogears import identity
import urlparse
import urllib

def get_user_office():
    try:
        office = identity.current.user.office
    except:
        office = None
    return office


def get_referer():
    header = request.headerMap
    result = header.get('Referer', header.get('Host','./'))
    if not ('/' in result):
        result ='/'+result
    return  result
def get_host_url():
    header = request.headerMap
    result = header.get('Host','./')
    if not ('/' in result):
        result ='/'+result
    return  result
def get_by_key_and_delete(key, data, default=''):
    if data.has_key(key):
        res = data[key]
        del data[key]
    else:
        res = default
    return res

def isint(source):
    try:
        int(source.strip().split()[0])
    except (ValueError, IndexError):
        return False
    return True

def urlparse_qs(url, keep_blank_values=0, strict_parsing=0):
    """Parse a URL query string and return the components as a dictionary.

        Based on the cgi.parse_qs method.This is a utility function provided
        with urlparse so that users need not use cgi module for
        parsing the url query string.

        Arguments:

        url: URL with query string to be parsed

        keep_blank_values: flag indicating whether blank values in
            URL encoded queries should be treated as blank strings.
            A true value indicates that blanks should be retained as
            blank strings.  The default false value indicates that
            blank values are to be ignored and treated as if they were
            not included.

        strict_parsing: flag indicating what to do with parsing errors.
            If false (the default), errors are silently ignored.
            If true, errors raise a ValueError exception.
    """

    myUnquote = lambda s: urllib.unquote(str(s)).replace('+', ' ')

    scheme, netloc, url, params, querystring, fragment = urlparse.urlparse(url)

    pairs = [s2 for s1 in url.split('&') for s2 in s1.split(';')]
    query = []
    for name_value in pairs:
        if not name_value and not strict_parsing:
            continue
        nv = name_value.split('=', 1)
        if len(nv) != 2:
            if strict_parsing:
                raise ValueError, "bad query field: %r" % (name_value,)
            # Handle case of a control-name with no equal sign
            if keep_blank_values:
                nv.append('')
            else:
                continue
        if len(nv[1]) or keep_blank_values:
            name = myUnquote(nv[0])
            value = myUnquote(nv[1])
            query.append((name, value))

    result = {}
    for name, value in query:
        if name in result:
            result[name].append(value)
        else:
            result[name] = [value]
    for x in result:
        if len(result[x]) == 1:
            result[x] = result[x][0]
    return result

def find_class(class_name):
    return classregistry.findClass(class_name)

def buildChunksOr(user,model_name):
    model = find_class('AuthUser'+model_name)
    print 'aaaaa', model
    from mnemoply.model.auth import AuthUser
    print AuthUser.selectBy(person=3)
    select = model.selectBy(user=user)
    column_name = model_name.lower()
    print [getattr(uo, column_name )for uo in select]

    query="( "
    if (None in [getattr(uo, column_name )for uo in select]):
     return "1=1"
    lst=[ "(%s_id = %s)" %(column_name, getattr(uo, column_name).id) for uo in select]
    if len(lst)>0:
       query += " OR ".join(lst)
    else: return "1=0"
    query += ")"
    print query
    return query



def get_filter_by_user(self, user, filter_name ):
    print "ggggggggggffffffffffffffff"
    print cherrypy.session
    flt = cherrypy.session.get(user.session +'_'+filter_name)
    print flt
    if not flt:
        flt = getattr( user,'filter_'+ filter_name)
        print filter_name, flt
        cherrypy.session[user.session +'_'+filter_name] = flt
    return '(%s)'%flt


class PhoneFormat(object):
    @staticmethod
    def bad_str(rus=False):
        if (rus):
            return _('Incorrectly dialed')
        return 'Incorrectly dialed'

    @staticmethod
    def is_phone_from_dict(value):
        if not isinstance(value, dict):
            return False
        if not (value.has_key('code') and value.has_key('num')):
            return False
        new_value = PhoneFormat.check_empty(value)
        if len(new_value['code']) + len(new_value['num'])!=10:
            return False
        return True
    @staticmethod
    def check_empty(dict_value):
        num = str(dict_value['num']).strip()
        code = str(dict_value['code']).strip()
        if not (len(code) + len(num)):
            code = '000'
            num = '0000000'
        if not len(code):
            code = '0'*(10-len(num))
        if not len(num):
            num = '0'*(10-len(code))
        return dict(code=code,num=num)

    @staticmethod
    def dict_to_str(value):
        
        if value is None:
            return None
        if not (PhoneFormat.is_phone_from_dict(value)):
            return PhoneFormat.bad_str()
        new_value = PhoneFormat.check_empty(value)
        num = new_value['num']
        code = new_value['code']
        num_full = "%s-%s-%s"%(num[:-4],num[-4:-2],num[-2:])
        return "+7-(%s)-%s"%(code,num_full)

    @staticmethod
    def str_to_dict(value):
        if value is None:
            return None
        beg_num = value.find(')')
        return dict (code=value[4:beg_num],num=value[beg_num+2:].replace('-',''))
    
def multiple_remove(st, *args):
    if not args:
        args = ['-', ')' '(']
    for a in args:
        st = st.replace(a, '')
    return st
def multiple_replace(st, **kw):
    for v in kw.values():
        if v is None:
            v = ''
    for k, v in kw.items():
        st = st.replace(k, v)
    return st
